import { ref, onUnmounted } from 'vue';
import { Cartesian3, Color, Entity, PolygonHierarchy, Viewer } from 'cesium';
import { Img, Img1 } from '@/components/cesium/map.config';
import jinanGeoJSON from '@/utils/jinanxzqh.json';

interface UseCesiumMapOptions {
  containerRef: any;
  onMapReady?: () => void;
}

export const useCesiumMap = (options: UseCesiumMapOptions) => {
  const { containerRef, onMapReady } = options;

  const viewer = ref<Viewer | null>(null);
  const isInitialized = ref(false);

  // 初始化地图
  const initMap = (forceReinit = false) => {
    if (!containerRef.value) {
      console.error('容器引用不可用');
      return;
    }

    if (isInitialized.value && !forceReinit) {
      console.log('地图已初始化，跳过重复初始化');
      return;
    }

    // 如果强制重新初始化，先销毁现有地图
    if (forceReinit && viewer.value) {
      viewer.value.destroy();
      viewer.value = null;
      isInitialized.value = false;
    }

    try {
      // 创建 Cesium Viewer
      viewer.value = new Viewer(containerRef.value, {
        baseLayer: false,
        geocoder: false,
        homeButton: false,
        sceneModePicker: false,
        baseLayerPicker: false,
        navigationHelpButton: false,
        animation: false,
        shouldAnimate: false,
        timeline: false,
        fullscreenButton: false,
        selectionIndicator: false,
        infoBox: false,
        contextOptions: {
          webgl: {
            alpha: true
          }
        }
      });

      // 清除默认图层
      viewer.value.imageryLayers.removeAll();

      // 添加天地图影像
      viewer.value.imageryLayers.addImageryProvider(Img);
      viewer.value.imageryLayers.addImageryProvider(Img1);

      // 设置相机位置
      viewer.value.camera.setView({
        destination: Cartesian3.fromDegrees(117.140035075, 36.798747059, 300000)
      });

      // 设置最大缩放距离
      viewer.value.scene.screenSpaceCameraController.maximumZoomDistance = 300000;

      // 启用深度检测
      viewer.value.scene.screenSpaceCameraController.enableTilt = true;

      // 添加济南市遮罩
      addRegionalMask();

      isInitialized.value = true;
      console.log('地图初始化完成');

      // 通知地图准备就绪
      if (onMapReady) {
        onMapReady();
      }
    } catch (error) {
      console.error('地图初始化失败:', error);
    }
  };

  // 添加济南市遮罩
  const addRegionalMask = () => {
    if (!viewer.value) return;

    const maskpointArray = [];
    const coordinates = jinanGeoJSON.features[0].geometry.coordinates[0][0];
    for (let i = 0; i < coordinates.length; i++) {
      maskpointArray.push(coordinates[i][0]);
      maskpointArray.push(coordinates[i][1]);
    }
    const maskspoint = Cartesian3.fromDegreesArray(maskpointArray);

    // 创建外部区域的坐标数组
    const outerBoundary = Cartesian3.fromDegreesArray([0, 0, 10, 89, 160, 89, 160, 0]);

    // 创建多边形层次结构，包含外部区域和挖空区域
    const polygonHierarchy = new PolygonHierarchy(outerBoundary, [new PolygonHierarchy(maskspoint)]);

    const area = new Entity({
      id: new Date() + '2',
      polygon: {
        hierarchy: polygonHierarchy,
        material: Color.fromCssColorString('#5ec0f0').withAlpha(0.6) // 外部颜色
      }
    });

    viewer.value.entities.add(area);
  };

  // 销毁地图
  const destroyMap = () => {
    if (viewer.value) {
      viewer.value.destroy();
      viewer.value = null;
      isInitialized.value = false;
      console.log('地图已销毁');
    }
  };

  // 重置地图
  const resetMap = () => {
    destroyMap();
    initMap();
  };

  // 组件卸载时清理
  onUnmounted(() => {
    destroyMap();
  });

  return {
    viewer,
    isInitialized,
    initMap,
    destroyMap,
    resetMap
  };
};
